<template>
  <div class="knowledge-base-container">
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/ManageHome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>知识库管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/KnowBases' }">知识库列表</el-breadcrumb-item>
      <el-breadcrumb-item>文档列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 知识库基础信息 -->
    <el-card class="base-info">
      <div class="info-item">
        <label>知识库名称：</label>
        <span>{{ knowledgeBase.name }}</span>
      </div>
      <div class="info-item">
        <label>知识库描述：</label>
        <span>{{ knowledgeBase.des }}</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info-item">
            <label>文档数量：</label>
            <span>{{ knowledgeBase.docCount }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <label>总大小：</label>
            <span>{{ formatSize(knowledgeBase.totalSize) }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 文档列表 -->
    <el-card class="document-list">
      <div class="operation-bar">
        <el-button type="primary" @click="handleAdd">新增文档</el-button>
        <el-input v-model="searchKey" placeholder="搜索文档名称" style="width: 200px; margin-left: 10px;" clearable />
      </div>

      <el-table :data="filteredDocuments" border style="width: 100%" size="small">
        <el-table-column prop="name" label="文档名称" />
        <el-table-column prop="fileName" label="文件名" />
        <el-table-column prop="type" label="文档来源">
          <template #default="{ row }">
            <el-tag>{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sliceNum" label="切片数量" />
        <el-table-column prop="sliceStatus" label="向量化状态">
          <template #default="{ row }">
            <el-tag :type="statusType(row.sliceStatus)">
              {{ row.sliceStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小">
          <template #default="{ row }">
            {{ formatSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination :current-page="pagination.current" :page-size="pagination.size" :total="pagination.total"
        @current-change="handlePageChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="上传文档" name="upload">
          <el-form label-width="80px" style="margin-top: 20px;">
            <el-form-item label="选择文件">
              <el-upload class="upload-demo" drag action="/api/upload" :on-success="handleUploadSuccess"
                :on-error="handleUploadError" :before-upload="beforeUpload" :file-list="fileList">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">支持PDF/DOCX/TXT/JSON格式文件，大小不超过100MB</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="手动录入" name="manual">
          <el-form :model="form" label-width="80px" :rules="rules" ref="form">
            <el-form-item label="文档名称" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="内容" prop="fileName">
              <el-input type="textarea" v-model="form.content" rows="10"/>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ submitting ? '提交中...' : '确定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      knowId: 1,
      knowledgeBase: {
        id: 1,
        name: '示例知识库',
        des: '这是一个示例知识库',
        docCount: 15,
        totalSize: 1024 * 1024 * 5
      },
      activeTab: 'upload',
      documents: [],
      searchKey: '',
      dialogVisible: false,
      currentAction: 'add', // 'add' or 'edit'
      form: {
        id: null,
        knowledgeId:1,
        name: '',
        fileName: '',
        type: 'upload',
        sliceNum: 0,
        sliceStatus: 'pending',
        size: 0,
        url:"",
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.currentAction === 'add' ? '新增文档' : '编辑文档'
    },
    filteredDocuments() {
      return this.documents.filter(item =>
        item.name.includes(this.searchKey)
      ).slice(
        (this.pagination.current - 1) * this.pagination.size,
        this.pagination.current * this.pagination.size
      )
    }
  },

  created() {
    // 模拟初始化数据
    this.initData();
  },

  methods: {
    initData() {
      this.knowId = this.$route.params.id;
      this.documents = Array.from({ length: 15 }, (_, i) => ({
        id: i + 1,
        name: `文档 ${i + 1}`,
        fileName: `file${i + 1}.pdf`,
        type: ['upload', 'input'][i % 2],
        sliceNum: Math.floor(Math.random() * 10),
        sliceStatus: ['pending', 'processing', 'success', 'error'][i % 4],
        size: 1024 * (i + 1)
      }))
      this.pagination.total = this.documents.length
    },
    formatSize(size) {
      if (size < 1024) return size + 'B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB'
      return (size / (1024 * 1024)).toFixed(2) + 'MB'
    },

    statusType(status) {
      const types = {
        success: 'success',
        processing: 'primary',
        error: 'danger',
        pending: 'warning'
      }
      return types[status] || 'info'
    },

    handleAdd() {
      this.currentAction = 'add'
      this.form = {
        id: null,
        name: '',
        fileName: '',
        type: 'upload',
        sliceNum: 0,
        sliceStatus: 'pending',
        size: 0
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.$router.push({
        path: "/DocSilceManage",
        query: {
          knowId: this.knowId,
          docId:  row.id
        }
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除该文档？', '提示', {
        type: 'warning'
      }).then(() => {
        this.documents = this.documents.filter(item => item.id !== row.id)
        this.knowledgeBase.docCount--
      })
    },

    handleSubmit() {
      if (this.currentAction === 'add') {
        this.documents.unshift({
          ...this.form,
          id: Date.now()
        })
        this.knowledgeBase.docCount++
      } else {
        const index = this.documents.findIndex(item => item.id === this.form.id)
        this.documents.splice(index, 1, this.form)
      }
      this.dialogVisible = false
    },

    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('文件大小不能超过100MB')
      }
      return isLt100M
    },
    handleUploadSuccess(response, file) {
      this.submitting = false
      this.fileList = []
      this.$message.success('上传成功')
      // 这里处理上传成功后的逻辑，例如添加到文档列表
      this.documents.unshift({
        ...response.data,  // 假设返回上传文件信息
        id: Date.now(),
        sliceStatus: 'pending'
      })
      this.dialogVisible = false
    },

    handleUploadError(err) {
      this.submitting = false
      this.$message.error('上传失败，请重试')
    },
    handleSubmit() {
      if (this.activeTab === 'upload') {
        if (this.fileList.length === 0) {
          this.$message.warning('请先选择要上传的文件')
          return
        }
        this.submitting = true
        // 自动触发上传
      } else {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.submitting = true
            // 模拟异步提交
            setTimeout(() => {
              if (this.currentAction === 'add') {
                this.documents.unshift({
                  ...this.form,
                  id: Date.now(),
                  sliceNum: 0,
                  sliceStatus: 'pending'
                })
                this.knowledgeBase.docCount++
              } else {
                const index = this.documents.findIndex(item => item.id === this.form.id)
                this.documents.splice(index, 1, this.form)
              }
              this.submitting = false
              this.dialogVisible = false
            }, 500)
          }
        })
      }
    },


    handlePageChange(page) {
      this.pagination.current = page
    }
  }
}
</script>

<style scoped>
.knowledge-base-container {
  padding: 20px;
}

.base-info {
  margin-bottom: 20px;
}

.info-item {
  margin: 10px 0;
}

.info-item label {
  color: #909399;
  margin-right: 10px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>